package com.chuangke.common.db.mybatisplus;

import java.util.Date;

import org.apache.ibatis.reflection.MetaObject;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.chuangke.common.utils.SecurityUtils;

/**
 * 自定义公共字段填充处理器
 */
//@Component
//@Configuration
public class CkMetaObjectHandler implements MetaObjectHandler {

	private static final String[] CREATE_COLS_BY = { "createdBy", "updatedBy", "commentBy" };
	private static final String[] CREATE_COLS_AT = { "createdAt", "updatedAt", "commentAt" };

	private static final String[] UPDATE_COLS_BY = { "updatedBy" };
	private static final String[] UPDATE_COLS_AT = { "updatedAt" };

	/**
	 * 插入填充
	 * 
	 * @param metaObject
	 */
	@Override
	public void insertFill(MetaObject metaObject) {
		String username = SecurityUtils.getUserId();
		for (String col : CREATE_COLS_BY) {
			if(!metaObject.hasSetter(col)) {
				continue ;
			}
			Object value = getFieldValByName(col, metaObject);
			if(value == null) {
				setFieldValByName(col, username, metaObject);
			}
		}

		for (String col : CREATE_COLS_AT) {
			if(!metaObject.hasSetter(col)) {
				continue ;
			}
			Object value = getFieldValByName(col, metaObject);
			if(value == null) {
				setFieldValByName(col, new Date(), metaObject);
			}
		}

	}

	/**
	 * 修改填充
	 * 
	 * @param metaObject
	 */
	@Override
	public void updateFill(MetaObject metaObject) {
		String username = SecurityUtils.getUserId();
		for (String col : UPDATE_COLS_BY) {
			if(!metaObject.hasSetter(col)) {
				continue ;
			}
			// 获取公共字段的值
			setFieldValByName(col, username, metaObject);
		}

		for (String col : UPDATE_COLS_AT) {
			if(!metaObject.hasSetter(col)) {
				continue ;
			}
			// 获取公共字段的值
			setFieldValByName(col, new Date(), metaObject);
		}
	}
}